const dbName = "TelemetryDB";
const storeName = "telemetry";
const dbVersion = 3; // 更新版本号

let dbPromise = null;

export function db() {
    if (!dbPromise) {
        dbPromise = new Promise((resolve, reject) => {
            const request = indexedDB.open(dbName, dbVersion);

            request.onupgradeneeded = (event) => {
                const db = event.target.result;
                const oldVersion = event.oldVersion;
                const transaction = event.target.transaction;
                let store;

                if (!db.objectStoreNames.contains(storeName)) {
                    // 初次创建
                    store = db.createObjectStore(storeName, {keyPath: "id", autoIncrement: true});
                    store.createIndex("dateTimeIndex", "dateTime", {unique: false});
                    store.createIndex("timestampIndex", "timestamp", {unique: false});
                } else {
                    store = transaction.objectStore(storeName);

                    // 版本2升级到3：添加timestamp索引
                    if (oldVersion < 3) {
                        if (!store.indexNames.contains("timestampIndex")) {
                            store.createIndex("timestampIndex", "timestamp", {unique: false});
                        }
                        // 遍历数据并添加timestamp字段
                        const cursorRequest = store.openCursor();
                        cursorRequest.onsuccess = (e) => {
                            const cursor = e.target.result;
                            if (cursor) {
                                const item = cursor.value;
                                if (item.timestamp === undefined) {
                                    item.timestamp = new Date(item.dateTime).getTime();
                                    cursor.update(item);
                                }
                                cursor.continue();
                            }
                        };
                    }
                }
            };

            request.onsuccess = () => resolve(request.result);
            request.onerror = (e) => reject(e.target.error);
        });
    }
    return dbPromise;
}

export async function saveDataToDB(data) {
    const dbObj = await db();

    return new Promise((resolve, reject) => {
        const transaction = dbObj.transaction(storeName, "readwrite");
        const store = transaction.objectStore(storeName);

        // 确保timestamp存在
        const newData = {
            ...data,
            timestamp: data.timestamp || new Date(data.dateTime).getTime()
        };

        store.add(newData);
        transaction.oncomplete = () => resolve();
        transaction.onerror = (e) => reject(e.target.error);
    });
}

export async function getDataByDateRange(timestampRange) {
    const dbObj = await db();
    const [start, end] = timestampRange;

    return new Promise((resolve, reject) => {
        const transaction = dbObj.transaction(storeName, "readonly");
        const store = transaction.objectStore(storeName);
        const index = store.index("timestampIndex");
        const range = IDBKeyRange.bound(start, end);

        const cursorRequest = index.openCursor(range);
        const results = [];

        cursorRequest.onsuccess = (e) => {
            const cursor = e.target.result;
            if (cursor) {
                results.push(cursor.value);
                cursor.continue(); // 自动推进到下一条，无需手动分批次
            } else {
                resolve(results);
            }
        };

        cursorRequest.onerror = (e) => reject(e.target.error);
    });
}
